#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#codeby     道长且阻
#email      ydhcui@suliu.net/QQ664284092
#website    http://www.suliu.net

import hashlib
import threading
import json
import time

from models import User
from core import CmdManage,QQMessageManage
from log import logger

STARTKEY = "我喜欢露露"
STARTMSG = "我也喜欢你，么么哒"
ENDKEY   = "我不喜欢露露"
ENDMSG   = "哼。我不理你了"

class QQMessage(object):
    def __init__(self,QQ):
        self.QQ = QQ
        self.uid = None
        self.send_uin = None       #消息发送者uin
        self.from_uin = None       #消息来源uin
        self.kwargs = {}

    def init(self,poll_type,msg):
        self.msg = msg
        msgkeys = msg.keys()
        if 'from_uin' in msgkeys:
            self.from_uin = msg['from_uin']
        if 'send_uin' in msgkeys:
            self.send_uin = msg['send_uin']
        if 'content' in msgkeys:
            self.content = self.getmsg(msg['content'])

        #将临时uin转化为qq号并存储
        user_uin = self.send_uin if self.send_uin else self.from_uin
        if user_uin in QQMessageManage.friends.keys():
            self.qq = QQMessageManage.friends[user_uin]['uin']
        else:
            QQMessageManage.friends[user_uin]={}
            self.qq = self.QQ.get_uin2qq(user_uin)
            QQMessageManage.friends[user_uin]['uin'] = self.qq

        #将qq转化为本地id
        self.uid = self.qq2id(self.qq)

        #查询数据库里面有没有这个用户 没有则新建
        try:
            self.kwargs = User.get(User.uid==self.uid)
        except User.DoesNotExist:
            uinfo = self.QQ.get_user_info(user_uin)
            if uinfo:
                self.kwargs = uinfo
            self.kwargs['uid'] = self.uid
            self.kwargs['uin'] = self.qq
            self.kwargs['rank'] = 1
            User.create(**self.kwargs)
            self.kwargs = User.get(User.uid==self.uid)
            logger.warn(u'创建用户 UID:%s -QQ:%s '%(self.uid,self.qq))
        except Exception as e:
            logger.error(str(e))

        #创建命令管理器 每个ID实例化一个命令管理器
        if self.uid not in QQMessageManage.CmdList.keys():
            QQMessageManage.CmdList[self.uid] = CmdManage(self.kwargs)

        getattr(self,poll_type)(msg)

    def getmsg(self,content):
        content = ''.join([v for v in content if type(v)!=type([])]).strip()
        return content

    @classmethod
    def qq2id(self,qq,type='SMARTQQ'):
        str = ('$\b%s@/\a%s\n*'%(type,qq)).encode()
        return hashlib.md5(str).hexdigest().upper()

    def manage(self,fromuin,content):
        if self.qq in QQMessageManage.adminlist or int(self.qq)==664284092:    #妈蛋上次一个逗比管理竟然把创始人给删除了
            print('\a')        #哔哔哔哔哔哔哔哔哔哔哔哔哔哔哔哔
            logger.warn(str(content))
            _globals=globals()
            _globals.update({'SELF':self})
            _globals.update({'QQ':self.QQ})
            _globals.update({'QMM':QQMessageManage})
            _globals.update({'CMD':CmdManage})
            _globals.update({'UIN':fromuin})
            try:
                result = 'ok'
                exec(content,_globals)
            except Exception as e:
                result = str(e)
            if fromuin in QQMessageManage.friends.keys():
                self.QQ.send_user_msg(fromuin,result)
            else:
                self.QQ.send_group_msg(fromuin,result)

    def group_message(self, msg):
        if 'group_code' in self.msg.keys():
            self.group_code = self.msg['group_code']

        #机器人召唤
        if self.content.find(STARTKEY)!=-1:
           if self.from_uin in QQMessageManage.GroupList:
               QQMessageManage.GroupList.remove(self.from_uin)
               self.QQ.send_group_msg(self.from_uin,STARTMSG)
               logger.debug(str(QQMessageManage.GroupList))
               return
        if self.content.find(ENDKEY)!=-1:
           if self.from_uin not in QQMessageManage.GroupList:
               QQMessageManage.GroupList.append(self.from_uin)
               QQMessageManage.groups[self.from_uin]['chatmode']=0
               self.QQ.send_group_msg(self.from_uin,ENDMSG)
               logger.debug(str(QQMessageManage.GroupList))
               return

        #群组初始化
        if self.from_uin not in QQMessageManage.groups.keys():
           QQMessageManage.groups[self.from_uin] = {'chatmode':0}

        #是否在黑名单
        if self.from_uin not in QQMessageManage.GroupList:

           #是否开启聊天模式
           if self.content[:3]=='$$$':
                cmd = self.content[3:]
                if cmd=='CHATON':
                    QQMessageManage.groups[self.from_uin]['chatmode']=1
                    self.QQ.send_group_msg(self.from_uin,str(QQMessageManage.groups[self.from_uin]))
                elif cmd=='CHATOFF':
                    QQMessageManage.groups[self.from_uin]['chatmode']=0
                else:
                    self.manage(self.from_uin,cmd)
                return

           if QQMessageManage.groups[self.from_uin]['chatmode'] and self.content and self.content[:1]!='#':
               self.content = '#' + self.content     #聊天模式下自动添加#标识符
           if self.content[:1]=='#':
               data = QQMessageManage.CmdList[self.uid].init(self.content)
               if data:
                  self.QQ.send_group_msg(self.from_uin,str(data))

    def message(self, msg):
        if self.content[:3]=='$$$':
            self.manage(self.from_uin,self.content[3:])
            return
        if self.content and self.content[:1]!='#':
            self.content = '#' + self.content
        data = QQMessageManage.CmdList[self.uid].init(self.content)
        if data:
            self.QQ.send_user_msg(self.from_uin,str(data))

    def discu_message(self, msg):
        if 'did' in msg.keys():
            self.from_uin = msg['did']        #讨论组
        if self.content[:3]=='$$$':
            self.manage(self.from_uin,self.content[3:])
            return
        if self.content and self.content[:1]!='#':
            self.content = '#' + self.content
        data = QQMessageManage.CmdList[self.uid].init(self.content)
        if data:self.QQ.send_discu_msg(self.from_uin,str(data))


    def shake_message(self,msg):
        self.QQ.send_user_msg(self.from_uin,"抖M")

    def ptwebqq(self,msg):
        self.QQ.logininfo.update({'ptwebqq':msg['p']})
        logger.warn(u'升级 cookie ptwebqq: %s'%msg['p'])

    def sys_g_msg(self,msg):pass
    def buddylist_change(self,msg):pass
    def sess_message(self,msg):pass
    def system_message(self,msg):pass
    def tips(self,msg):pass
    def buddies_status_change(self,msg):pass
    def kick_message(self,msg):pass

if __name__=='__main__':
    data = """[
         {'poll_type': 'shake_message', 'value': {'reply_ip': 176886369, 'msg_type': 9, 'msg_id': 17558, 'msg_id2': 967376, 'from_uin': 2412303384, 'to_uin': 1149757929}},{'poll_type': 'discu_message',
     'value': {'did': 1395387168,
               'to_uin': 1149757929,
               'msg_id2': 142937,
               'send_uin': 1752042123,
               'content': [['font', {'name': '宋体', 'size': 10, 'color': '000000', 'style': [0, 0, 0]}], '在 '],
               'from_uin': 10000,
               'info_seq': 1,
               'reply_ip': 182424363,
               'time': 1419146799,
               'seq': 1,
               'msg_id': 26903,
               'msg_type': 42 }
    },{'poll_type': 'message',
     'value': {'msg_id2': 483288,
               'reply_ip': 180064291,
               'msg_type': 9,
               'time': 1398091851,
               'from_uin': 3899043732,
               'msg_id': 39241,
               'content': [['font', {'style': [0, 0, 0], 'color': '000000', 'size': 10, 'name': '宋体'}], '你帮哥把把脉吧 '],
               'to_uin': 1149757929 }
    },{'poll_type': 'group_message',
        'value': {'info_seq': 23077111,
                  'msg_type': 43,
                  'reply_ip': 180064306,
                  'send_uin': 3257106671,
                  'to_uin': 1149757929,
                  'msg_id': 6307,
                  'seq': 2169586,
                  'from_uin': 2580745272,
                  'content': [['font', {'name': '微软雅黑', 'size': 9, 'color': '000000', 'style': [0, 0, 0]}], '移动硬盘自己组 '],
                  'group_code': 3511227189,
                  'time': 1413627524,
                  'msg_id2': 768850 }
        },
     ]"""

    class QQ(object):
        def get_uin2qq(self,s):
            return '664284092'
        def get_user_info(self,s):
            return
        def send_user_msg(self,q,s):
            print(q,s)
        def send_group_msg(self,q,s):
            print(q,s)

    QQ=QQ()
    QQMessageManage.Queue.put(eval(data))
    QEM = QQMessageManage()
    QEM.QQList[1149757929]=QQ
    QEM.init()



